package com.itzxx.huazhun.utils

import android.text.TextUtils
import com.google.gson.Gson
import com.itzxx.huazhun.data.model.UserInfo
import com.itzxx.huazhun.data.model.UserPermissionInfo
import com.itzxx.library_base_ktx.base.appContext
import com.tencent.mmkv.MMKV

object UserCacheHelper {

    private var kv: MMKV


    fun getToken(): String {
        return kv.decodeString("token", "").toString()
    }

    fun putToken(token: String) {
        kv.encode("token", token)
    }

    fun putRefreshToken(refreshToken: String) {
        kv.encode("refreshToken", refreshToken)
    }

    fun getRefreshToken(): String {
        return kv.decodeString("refreshToken", "").toString()
    }

    fun getPassword(): String {
        return kv.decodeString("password", "").toString()
    }


    fun putPassword(password: String) {
        kv.encode("password", password)
    }

    fun getTenantId(): String {
        return kv.decodeString("Tenant-id", "").toString()
    }

    fun putTenantId(tenantId: String) {
        kv.encode("Tenant-id", tenantId)
    }

    fun getUserPermission(): UserPermissionInfo? {
        val jsonUserPermission = kv.decodeString("UserPermission", "").toString()
        if (!TextUtils.isEmpty(jsonUserPermission)) {

            return Gson().fromJson(jsonUserPermission, UserPermissionInfo::class.java)
        } else {
            return null
        }
    }

    fun putUserPermission(json: UserPermissionInfo) {
        kv.encode("UserPermission", Gson().toJson(json))
    }

    fun putIsOffline(isOffline: Boolean) {
        kv.encode("isOffline", isOffline)
    }

    fun getUserInfo(): UserInfo? {
        val jsonUserInfo = kv.decodeString("UserInfo", "").toString()
        return if (!TextUtils.isEmpty(jsonUserInfo)) {
            Gson().fromJson(jsonUserInfo, UserInfo::class.java)
        } else {
            null
        }
    }

    fun putUserInfo(json: UserInfo) {
        kv.encode("UserInfo", Gson().toJson(json))
    }

    fun isAdmin(): Boolean {
        val userPermission = getUserPermission()
        if (userPermission != null) {
            for (role in userPermission.roles) {
                if (role.contains("admin")) {
                    return true
                }
            }
        }
        return false
    }


    fun isOffline(): Boolean {
        return kv.decodeBool("isOffline")
    }

    fun putBleDevice(json: String) {
        kv.encode("bledevice", json)
    }

    fun getBleDevice(): String? {
        return kv.decodeString("bledevice")
    }


    init {
        MMKV.initialize(appContext)
        kv = MMKV.defaultMMKV()
    }
}